import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param grid int整型ArrayList<ArrayList<>> 
     * @return int整型
     */
    private boolean[][] visited;
    private ArrayList<ArrayList<Integer>> list;
    public int rotApple (ArrayList<ArrayList<Integer>> grid) {
        // write code here
        int n = grid.size();
        int m = grid.get(0).size();
        fun(m);
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < n; i++) {
            ArrayList<Integer> tmp = new ArrayList<>();
            tmp.add(0);
            for(int j = 0; j < m + 2; j++) {
                int val = grid.get(i).get(j);
                if(val == 2) {
                    map.put(i, j);
                }
                tmp.add(val);
            }
            tmp.add(0);
        }
        fun(m);
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int row = entry.getKey();
            int col = entry.getValue();
            rot(row, col);
        }

        return -1;
    }

    private void fun(int col) {
        ArrayList<Integer> tmp = new ArrayList<>();
        for(int i = 0; i < col + 2; i++) {
            tmp.add(0);
        }
        list.add(new ArrayList<>(tmp));
    }

    private void rot(int row, int col) {
        if(row == 0 || row == list.size()-1 || col == 0 || col == list.get(0).size()-1) {
            return;
        }
        if(list.get(row-1).get(col) == 1) {
            list.get(row-1).set(col, 2);
            rot(row-1, col);
        }
        if(list.get(row+1).get(col) == 1) {
            list.get(row+1).set(col, 2);
            rot(row+1, col);
        }
        if(list.get(row).get(col-1) == 1) {
            list.get(row).set(col-1, 2);
            rot(row, col-1);
        }
        if(list.get(row).get(col+1) == 2) {
            list.get(row).set(col+1, 2);
            rot(row, col+1);
        }
    }
}